<template>
  <div class="typescript-demo">
    <h2 class="section-title">TypeScript 特性演示</h2>
    
    <div class="demo-grid">
      <!-- 类型系统 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>类型系统</h3>
          <button class="code-toggle" @click="toggleCode('types')">
            {{ showCode.types ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.types">
            <pre class="code-viewer"><code>// 基本类型
const name: string = "TypeScript";
const version: number = 5.0;
const isStable: boolean = true;
const features: string[] = ["类型", "泛型", "装饰器"];

// 联合类型和类型别名
type ID = string | number;
let userId: ID = "user-123";
userId = 123; // 同样有效

// 接口定义
interface User {
  id: ID;
  name: string;
  email?: string;  // 可选属性
  readonly createdAt: Date;  // 只读属性
}

// 字面量类型
type Theme = "light" | "dark" | "system";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

// 类型断言
const input = document.getElementById("user-input") as HTMLInputElement;
const length = (input.value as string).length;</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">基本类型:</span>
                <span class="feature-value">string, number, boolean, array</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">联合类型:</span>
                <span class="feature-value">string | number</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">字面量类型:</span>
                <span class="feature-value">"light" | "dark" | "system"</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="typesDemo.selectedType">
                  <option value="basic">基本类型</option>
                  <option value="union">联合类型</option>
                  <option value="literal">字面量类型</option>
                  <option value="interface">接口类型</option>
                </select>
                <input v-model="typesDemo.input" :placeholder="getTypePlaceholder()">
                <button @click="processTypeInput">验证类型</button>
              </div>
              <div class="result-display" v-if="typesDemo.result">
                {{ typesDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 泛型 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>泛型编程</h3>
          <button class="code-toggle" @click="toggleCode('generics')">
            {{ showCode.generics ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.generics">
            <pre class="code-viewer"><code>// 泛型函数
function identity&lt;T&gt;(arg: T): T {
  return arg;
}

// 泛型接口
interface Response&lt;T&gt; {
  data: T;
  status: number;
  message: string;
}

// 泛型类
class DataContainer&lt;T&gt; {
  private data: T[];
  
  constructor(initialData: T[]) {
    this.data = initialData;
  }
  
  add(item: T): void {
    this.data.push(item);
  }
  
  getAll(): T[] {
    return this.data;
  }
}

// 泛型约束
interface Lengthwise {
  length: number;
}

function getLength&lt;T extends Lengthwise&gt;(arg: T): number {
  return arg.length;
}</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">泛型函数:</span>
                <span class="feature-value">identity&lt;T&gt;(arg: T): T</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">泛型接口:</span>
                <span class="feature-value">Response&lt;T&gt;</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">泛型约束:</span>
                <span class="feature-value">T extends Lengthwise</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="genericsDemo.type">
                  <option value="function">泛型函数</option>
                  <option value="interface">泛型接口</option>
                  <option value="class">泛型类</option>
                  <option value="constraint">泛型约束</option>
                </select>
                <input v-model="genericsDemo.input" :placeholder="getGenericPlaceholder()">
                <button @click="processGenericInput">生成示例</button>
              </div>
              <div class="result-display" v-if="genericsDemo.result">
                {{ genericsDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 高级类型 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>高级类型</h3>
          <button class="code-toggle" @click="toggleCode('advanced')">
            {{ showCode.advanced ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.advanced">
            <pre class="code-viewer"><code>// 映射类型
type Readonly&lt;T&gt; = {
  readonly [P in keyof T]: T[P];
};

// 条件类型
type NonNullable&lt;T&gt; = T extends null | undefined ? never : T;

// 工具类型
type Partial&lt;T&gt; = {
  [P in keyof T]?: T[P];
};</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">只读类型:</span>
                <span class="feature-value">{{ advancedDemo.readonly }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">可选类型:</span>
                <span class="feature-value">{{ advancedDemo.partial }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <input v-model="advancedDemo.input" placeholder="输入对象属性">
                <select v-model="advancedDemo.type">
                  <option value="readonly">只读</option>
                  <option value="partial">可选</option>
                </select>
                <button @click="processAdvancedType">转换</button>
              </div>
              <div class="result-display" v-if="advancedDemo.result">
                {{ advancedDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 枚举类型 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>枚举类型</h3>
          <button class="code-toggle" @click="toggleCode('enum')">
            {{ showCode.enum ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.enum">
            <pre class="code-viewer"><code>// 数字枚举
enum Direction {
  Up = 1,
  Down,
  Left,
  Right
}

// 字符串枚举
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

// 常量枚举
const enum Size {
  Small = "S",
  Medium = "M",
  Large = "L"
}</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">数字枚举:</span>
                <span class="feature-value">{{ enumDemo.numeric }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">字符串枚举:</span>
                <span class="feature-value">{{ enumDemo.string }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="enumDemo.type">
                  <option value="direction">方向</option>
                  <option value="color">颜色</option>
                  <option value="size">尺寸</option>
                </select>
                <select v-model="enumDemo.value">
                  <option v-for="option in enumDemo.options" :key="option" :value="option">
                    {{ option }}
                  </option>
                </select>
                <button @click="processEnum">获取枚举值</button>
              </div>
              <div class="result-display" v-if="enumDemo.result">
                {{ enumDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 类型断言 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>类型断言</h3>
          <button class="code-toggle" @click="toggleCode('assertion')">
            {{ showCode.assertion ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.assertion">
            <pre class="code-viewer"><code>// 尖括号语法
let someValue: any = "this is a string";
let strLength: number = (&lt;string&gt;someValue).length;

// as 语法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

// 非空断言
function processText(text: string | null) {
  console.log(text!.length);
}

// 常量断言
const req = { url: "https://example.com" } as const;</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">类型断言:</span>
                <span class="feature-value">{{ assertionDemo.basic }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">非空断言:</span>
                <span class="feature-value">{{ assertionDemo.nonNull }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <input v-model="assertionDemo.input" placeholder="输入任意值">
                <select v-model="assertionDemo.type">
                  <option value="string">字符串</option>
                  <option value="number">数字</option>
                  <option value="boolean">布尔值</option>
                </select>
                <button @click="processAssertion">类型断言</button>
              </div>
              <div class="result-display" v-if="assertionDemo.result">
                {{ assertionDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 装饰器 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>装饰器</h3>
          <button class="code-toggle" @click="toggleCode('decorator')">
            {{ showCode.decorator ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.decorator">
            <pre class="code-viewer"><code>// 类装饰器
@sealed
class Example {
  // ...
}

// 方法装饰器
class Example {
  @log
  greet(message: string) {
    return `Hello, ${message}`;
  }
}

// 属性装饰器
class Example {
  @format("Hello, %s")
  greeting: string;
}

// 参数装饰器
class Example {
  greet(@required name: string) {
    return `Hello, ${name}`;
  }
}</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">类装饰器:</span>
                <span class="feature-value">{{ decoratorDemo.class }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">方法装饰器:</span>
                <span class="feature-value">{{ decoratorDemo.method }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <input v-model="decoratorDemo.input" placeholder="输入消息">
                <select v-model="decoratorDemo.type">
                  <option value="log">日志装饰器</option>
                  <option value="format">格式化装饰器</option>
                  <option value="validate">验证装饰器</option>
                </select>
                <button @click="processDecorator">应用装饰器</button>
              </div>
              <div class="result-display" v-if="decoratorDemo.result">
                {{ decoratorDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 类型工具 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>类型工具</h3>
          <button class="code-toggle" @click="toggleCode('utility')">
            {{ showCode.utility ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.utility">
            <pre class="code-viewer"><code>// Pick - 选择部分属性
type User = {
  id: number;
  name: string;
  email: string;
  age: number;
};
type UserBasic = Pick&lt;User, 'name' | 'age'&gt;;

// Omit - 排除部分属性
type UserPublic = Omit&lt;User, 'email'&gt;;

// Record - 创建键值对类型
type Roles = 'admin' | 'user' | 'guest';
type RoleConfig = Record&lt;Roles, { permissions: string[] }&gt;;

// ReturnType - 获取函数返回类型
function getData() {
  return { id: 1, value: 'test' };
}
type DataType = ReturnType&lt;typeof getData&gt;;</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">Pick:</span>
                <span class="feature-value">{{ utilityDemo.pick }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">Omit:</span>
                <span class="feature-value">{{ utilityDemo.omit }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">Record:</span>
                <span class="feature-value">{{ utilityDemo.record }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="utilityDemo.type">
                  <option value="pick">Pick</option>
                  <option value="omit">Omit</option>
                  <option value="record">Record</option>
                </select>
                <input v-model="utilityDemo.input" placeholder="输入属性（用逗号分隔）">
                <button @click="processUtility">应用工具类型</button>
              </div>
              <div class="result-display" v-if="utilityDemo.result">
                {{ utilityDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 模块系统 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>模块系统</h3>
          <button class="code-toggle" @click="toggleCode('module')">
            {{ showCode.module ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.module">
            <pre class="code-viewer"><code>// 导出声明
export interface User {
  id: number;
  name: string;
}

export type UserRole = 'admin' | 'user';

export class UserService {
  getUser(id: number): User {
    // ...
  }
}

// 导入声明
import { User, UserRole } from './types';
import type { UserConfig } from './config';

// 命名空间
namespace Validation {
  export interface StringValidator {
    isValid(s: string): boolean;
  }
}

// 动态导入
const loadModule = async () => {
  const module = await import('./module');
  return module.default;
};</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">导出类型:</span>
                <span class="feature-value">{{ moduleDemo.export }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">导入类型:</span>
                <span class="feature-value">{{ moduleDemo.import }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">命名空间:</span>
                <span class="feature-value">{{ moduleDemo.namespace }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="moduleDemo.type">
                  <option value="export">导出</option>
                  <option value="import">导入</option>
                  <option value="namespace">命名空间</option>
                </select>
                <input v-model="moduleDemo.input" placeholder="输入类型名称">
                <button @click="processModule">生成代码</button>
              </div>
              <div class="result-display" v-if="moduleDemo.result">
                {{ moduleDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 条件类型 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>条件类型</h3>
          <button class="code-toggle" @click="toggleCode('conditional')">
            {{ showCode.conditional ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.conditional">
            <pre class="code-viewer"><code>// 基础条件类型
type IsString&lt;T&gt; = T extends string ? true : false;

// 分配条件类型
type ToArray&lt;T&gt; = T extends any ? T[] : never;
type StrOrNumArray = ToArray&lt;string | number&gt;; // string[] | number[]

// infer 关键字
type GetReturnType&lt;T&gt; = T extends (...args: any[]) => infer R ? R : never;
type Unpacked&lt;T&gt; = T extends Promise&lt;infer U&gt; ? U : T;

// 条件类型约束
type NonNullable&lt;T&gt; = T extends null | undefined ? never : T;
type NonEmptyArray&lt;T&gt; = T extends [] ? never : T extends Array&lt;any&gt; ? T : never;</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">条件判断:</span>
                <span class="feature-value">{{ conditionalDemo.basic }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">类型推断:</span>
                <span class="feature-value">{{ conditionalDemo.infer }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="conditionalDemo.type">
                  <option value="isType">类型判断</option>
                  <option value="toArray">转数组</option>
                  <option value="returnType">返回类型</option>
                  <option value="nonNull">非空检查</option>
                </select>
                <input v-model="conditionalDemo.input" placeholder="输入类型表达式">
                <button @click="processConditional">分析类型</button>
              </div>
              <div class="result-display" v-if="conditionalDemo.result">
                {{ conditionalDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 映射类型 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>映射类型</h3>
          <button class="code-toggle" @click="toggleCode('mapped')">
            {{ showCode.mapped ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.mapped">
            <pre class="code-viewer"><code>// 基础映射类型
type Readonly&lt;T&gt; = {
  readonly [P in keyof T]: T[P];
};

// 可选属性映射
type Partial&lt;T&gt; = {
  [P in keyof T]?: T[P];
};

// 属性重映射
type Getters&lt;T&gt; = {
  [P in keyof T as `get${Capitalize&lt;string & P&gt;}`]: () => T[P];
};

// 条件类型映射
type PickByType&lt;T, U&gt; = {
  [P in keyof T as T[P] extends U ? P : never]: T[P];
};</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">属性映射:</span>
                <span class="feature-value">{{ mappedDemo.basic }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">键重映射:</span>
                <span class="feature-value">{{ mappedDemo.remap }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="mappedDemo.type">
                  <option value="readonly">只读映射</option>
                  <option value="partial">可选映射</option>
                  <option value="getters">Getter映射</option>
                  <option value="pickByType">类型选择</option>
                </select>
                <input v-model="mappedDemo.input" placeholder="输入属性（用逗号分隔）">
                <button @click="processMapped">生成类型</button>
              </div>
              <div class="result-display" v-if="mappedDemo.result">
                {{ mappedDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 类型推导 -->
      <div class="demo-card">
        <div class="demo-header">
          <h3>类型推导</h3>
          <button class="code-toggle" @click="toggleCode('inference')">
            {{ showCode.inference ? '隐藏代码' : '查看代码' }}
          </button>
        </div>
        <div class="demo-content">
          <div class="code-block" v-if="showCode.inference">
            <pre class="code-viewer"><code>// 返回类型推导
function createUser(name: string, age: number) {
  return { name, age, createdAt: new Date() };
}
type User = ReturnType&lt;typeof createUser&gt;;

// 参数类型推导
function map&lt;T, U&gt;(array: T[], callback: (item: T) => U): U[] {
  return array.map(callback);
}

// 上下文类型推导
const handler = (event: { target: HTMLElement }) => {
  console.log(event.target.id); // 类型安全访问
};

// 类型守卫
function isString(value: unknown): value is string {
  return typeof value === 'string';
}</code></pre>
          </div>
          <div class="demo-preview">
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-label">返回推导:</span>
                <span class="feature-value">{{ inferenceDemo.return }}</span>
              </div>
              <div class="feature-item">
                <span class="feature-label">参数推导:</span>
                <span class="feature-value">{{ inferenceDemo.parameter }}</span>
              </div>
            </div>
            <div class="interactive-demo">
              <div class="input-group">
                <select v-model="inferenceDemo.type">
                  <option value="return">返回类型</option>
                  <option value="parameter">参数类型</option>
                  <option value="context">上下文类型</option>
                  <option value="guard">类型守卫</option>
                </select>
                <input v-model="inferenceDemo.input" placeholder="输入示例代码">
                <button @click="processInference">分析推导</button>
              </div>
              <div class="result-display" v-if="inferenceDemo.result">
                {{ inferenceDemo.result }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'

// 代码显示状态
const showCode = ref({
  types: false,
  generics: false,
  advanced: false,
  enum: false,
  assertion: false,
  decorator: false,
  utility: false,
  module: false,
  conditional: false,
  mapped: false,
  inference: false
})

const toggleCode = (section) => {
  showCode.value[section] = !showCode.value[section]
}

// 类型系统演示
const typesDemo = reactive({
  selectedType: 'basic',
  input: '',
  result: ''
})

const getTypePlaceholder = () => {
  switch (typesDemo.selectedType) {
    case 'basic':
      return '输入值（如：42 或 "hello"）'
    case 'union':
      return '输入 ID（字符串或数字）'
    case 'literal':
      return '输入主题（light/dark/system）'
    case 'interface':
      return '输入用户属性（如：name,email）'
    default:
      return '输入值'
  }
}

const processTypeInput = () => {
  if (!typesDemo.input) {
    typesDemo.result = '请输入值'
    return
  }

  try {
    switch (typesDemo.selectedType) {
      case 'basic':
        const value = typesDemo.input
        const type = typeof value
        if (type === 'string' || type === 'number' || type === 'boolean') {
          typesDemo.result = `类型: ${type}\n值: ${value}`
        } else {
          throw new Error('不支持的类型')
        }
        break
      case 'union':
        const id = typesDemo.input
        const isValid = !isNaN(Number(id)) || typeof id === 'string'
        typesDemo.result = isValid 
          ? `有效的 ID: ${id}\n类型: ${typeof id}` 
          : '无效的 ID 类型'
        break
      case 'literal':
        const theme = typesDemo.input.toLowerCase()
        if (['light', 'dark', 'system'].includes(theme)) {
          typesDemo.result = `有效的主题值: "${theme}"`
        } else {
          throw new Error('无效的主题值')
        }
        break
      case 'interface':
        const props = typesDemo.input.split(',').map(p => p.trim())
        const userInterface = props.map(p => `  ${p}: string;`).join('\n')
        typesDemo.result = `interface User {\n${userInterface}\n}`
        break
    }
  } catch (error) {
    typesDemo.result = `错误: ${error.message}`
  }
}

// 泛型演示
const genericsDemo = reactive({
  type: 'function',
  input: '',
  result: ''
})

const getGenericPlaceholder = () => {
  switch (genericsDemo.type) {
    case 'function':
      return '输入参数类型（如：number）'
    case 'interface':
      return '输入数据类型（如：User）'
    case 'class':
      return '输入数据项（用逗号分隔）'
    case 'constraint':
      return '输入约束接口名'
    default:
      return '输入值'
  }
}

const processGenericInput = () => {
  if (!genericsDemo.input) {
    genericsDemo.result = '请输入值'
    return
  }

  switch (genericsDemo.type) {
    case 'function':
      genericsDemo.result = `function process<T extends ${genericsDemo.input}>(value: T): T {
  // 处理逻辑
  return value;
}`
      break
    case 'interface':
      genericsDemo.result = `interface ApiResponse<T> {
  data: ${genericsDemo.input};
  status: number;
  message: string;
}`
      break
    case 'class':
      const items = genericsDemo.input.split(',').map(item => `"${item.trim()}"`)
      genericsDemo.result = `class Container<T> {
  private items: T[] = [${items.join(', ')}];
  
  add(item: T): void {
    this.items.push(item);
  }
  
  getAll(): T[] {
    return this.items;
  }
}`
      break
    case 'constraint':
      genericsDemo.result = `interface ${genericsDemo.input} {
  length: number;
}

function getLength<T extends ${genericsDemo.input}>(arg: T): number {
  return arg.length;
}`
      break
  }
}

// 高级类型演示
const advancedDemo = reactive({
  readonly: 'Readonly<User>',
  partial: 'Partial<User>',
  input: '',
  type: 'readonly',
  result: ''
})

const processAdvancedType = () => {
  if (!advancedDemo.input) {
    advancedDemo.result = '请输入对象属性'
    return
  }

  const properties = advancedDemo.input.split(',').map(prop => prop.trim())
  const obj = {}
  
  properties.forEach(prop => {
    obj[prop] = '示例值'
  })

  switch (advancedDemo.type) {
    case 'readonly':
      advancedDemo.result = `只读对象:\n${JSON.stringify(obj, null, 2)}\n(所有属性都是只读的)`
      break
    case 'partial':
      advancedDemo.result = `可选对象:\n${JSON.stringify(obj, null, 2)}\n(所有属性都是可选的)`
      break
  }
}

// 枚举演示
const enumDemo = reactive({
  numeric: 'Direction.Up = 1',
  string: 'Color.Red = "RED"',
  type: 'direction',
  value: '',
  options: ['Up', 'Down', 'Left', 'Right'],
  result: ''
})

// 监听枚举类型变化
watch(() => enumDemo.type, (newType) => {
  switch (newType) {
    case 'direction':
      enumDemo.options = ['Up', 'Down', 'Left', 'Right']
      break
    case 'color':
      enumDemo.options = ['Red', 'Green', 'Blue']
      break
    case 'size':
      enumDemo.options = ['Small', 'Medium', 'Large']
      break
  }
  enumDemo.value = enumDemo.options[0]
})

const processEnum = () => {
  if (!enumDemo.value) {
    enumDemo.result = '请选择枚举值'
    return
  }

  switch (enumDemo.type) {
    case 'direction':
      const directionMap = { Up: 1, Down: 2, Left: 3, Right: 4 }
      enumDemo.result = `枚举值: ${directionMap[enumDemo.value]}`
      break
    case 'color':
      enumDemo.result = `枚举值: "${enumDemo.value.toUpperCase()}"`
      break
    case 'size':
      const sizeMap = { Small: 'S', Medium: 'M', Large: 'L' }
      enumDemo.result = `枚举值: "${sizeMap[enumDemo.value]}"`
      break
  }
}

// 类型断言演示
const assertionDemo = reactive({
  basic: '<Type>value 或 value as Type',
  nonNull: 'value!.property',
  input: '',
  type: 'string',
  result: ''
})

const processAssertion = () => {
  if (!assertionDemo.input) {
    assertionDemo.result = '请输入值'
    return
  }

  try {
    switch (assertionDemo.type) {
      case 'string':
        const strValue = String(assertionDemo.input)
        assertionDemo.result = `字符串长度: ${strValue.length}`
        break
      case 'number':
        const numValue = Number(assertionDemo.input)
        if (isNaN(numValue)) throw new Error('无效的数字')
        assertionDemo.result = `数字值: ${numValue.toFixed(2)}`
        break
      case 'boolean':
        const boolValue = Boolean(assertionDemo.input)
        assertionDemo.result = `布尔值: ${boolValue}`
        break
    }
  } catch (error) {
    assertionDemo.result = `断言错误: ${error.message}`
  }
}

// 装饰器演示
const decoratorDemo = reactive({
  class: '@sealed class Example',
  method: '@log method()',
  input: '',
  type: 'log',
  result: ''
})

const processDecorator = () => {
  if (!decoratorDemo.input) {
    decoratorDemo.result = '请输入消息'
    return
  }

  switch (decoratorDemo.type) {
    case 'log':
      decoratorDemo.result = `[LOG] 方法被调用: ${decoratorDemo.input}`
      break
    case 'format':
      decoratorDemo.result = `格式化结果: Hello, ${decoratorDemo.input}`
      break
    case 'validate':
      if (decoratorDemo.input.length < 3) {
        decoratorDemo.result = '验证失败: 输入长度必须大于3'
      } else {
        decoratorDemo.result = '验证通过: ' + decoratorDemo.input
      }
      break
  }
}

// 类型工具演示
const utilityDemo = reactive({
  pick: 'Pick<T, K>',
  omit: 'Omit<T, K>',
  record: 'Record<K, T>',
  type: 'pick',
  input: '',
  result: ''
})

const processUtility = () => {
  if (!utilityDemo.input) {
    utilityDemo.result = '请输入属性'
    return
  }

  const properties = utilityDemo.input.split(',').map(prop => prop.trim())
  
  switch (utilityDemo.type) {
    case 'pick':
      utilityDemo.result = `type UserBasic = Pick<User, '${properties.join("' | '")}'>\n// 结果类型包含: ${properties.join(', ')}`
      break
    case 'omit':
      utilityDemo.result = `type UserPublic = Omit<User, '${properties.join("' | '")}'>\n// 结果类型排除: ${properties.join(', ')}`
      break
    case 'record':
      const example = properties.reduce((acc, prop) => {
        acc[prop] = { permissions: ['read', 'write'] }
        return acc
      }, {})
      utilityDemo.result = `type RoleConfig = Record<'${properties.join("' | '")}', { permissions: string[] }>\n// 示例值: ${JSON.stringify(example, null, 2)}`
      break
  }
}

// 模块系统演示
const moduleDemo = reactive({
  export: 'export type/interface/class',
  import: 'import type { T }',
  namespace: 'namespace N { }',
  type: 'export',
  input: '',
  result: ''
})

const processModule = () => {
  if (!moduleDemo.input) {
    moduleDemo.result = '请输入类型名称'
    return
  }

  switch (moduleDemo.type) {
    case 'export':
      moduleDemo.result = `// 导出接口
export interface ${moduleDemo.input} {
  id: number;
  name: string;
  createdAt: Date;
}

// 导出类型
export type ${moduleDemo.input}Key = keyof ${moduleDemo.input};

// 导出类
export class ${moduleDemo.input}Service {
  get${moduleDemo.input}(id: number): ${moduleDemo.input} {
    // 实现获取逻辑
    return { id, name: 'test', createdAt: new Date() };
  }
}`
      break
    case 'import':
      moduleDemo.result = `// 导入类型
import type { ${moduleDemo.input} } from './types';
import type { ${moduleDemo.input}Config } from './config';

// 导入实现
import { ${moduleDemo.input}Service } from './services';`
      break
    case 'namespace':
      moduleDemo.result = `namespace ${moduleDemo.input} {
  export interface Config {
    readonly id: string;
    options: Record<string, unknown>;
  }

  export class Service {
    constructor(private config: Config) {}
    
    initialize(): void {
      // 实现初始化逻辑
    }
  }
}`
      break
  }
}

// 条件类型演示
const conditionalDemo = reactive({
  basic: 'T extends U ? X : Y',
  infer: 'infer R in return type',
  type: 'isType',
  input: '',
  result: ''
})

const processConditional = () => {
  if (!conditionalDemo.input) {
    conditionalDemo.result = '请输入类型表达式'
    return
  }

  switch (conditionalDemo.type) {
    case 'isType':
      conditionalDemo.result = `type Is${conditionalDemo.input} = T extends ${conditionalDemo.input} ? true : false;`
      break
    case 'toArray':
      conditionalDemo.result = `type ToArray<T> = T extends any ? T[] : never;\ntype Result = ToArray<${conditionalDemo.input}>;`
      break
    case 'returnType':
      conditionalDemo.result = `type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;\ntype Result = GetReturnType<${conditionalDemo.input}>;`
      break
    case 'nonNull':
      conditionalDemo.result = `type NonNullable<T> = T extends null | undefined ? never : T;\ntype Result = NonNullable<${conditionalDemo.input}>;`
      break
  }
}

// 映射类型演示
const mappedDemo = reactive({
  basic: '[P in keyof T]: T[P]',
  remap: 'as `get${Capitalize<P>}`',
  type: 'readonly',
  input: '',
  result: ''
})

const processMapped = () => {
  if (!mappedDemo.input) {
    mappedDemo.result = '请输入属性'
    return
  }

  const properties = mappedDemo.input.split(',').map(prop => prop.trim())
  const interfaceProps = properties.map(prop => `  ${prop}: string;`).join('\n')
  
  switch (mappedDemo.type) {
    case 'readonly':
      mappedDemo.result = `interface Base {\n${interfaceProps}\n}\n\ntype ReadonlyBase = {\n  readonly [P in keyof Base]: Base[P];\n};`
      break
    case 'partial':
      mappedDemo.result = `interface Base {\n${interfaceProps}\n}\n\ntype PartialBase = {\n  [P in keyof Base]?: Base[P];\n};`
      break
    case 'getters':
      const getters = properties.map(prop => 
        `  get${prop[0].toUpperCase() + prop.slice(1)}: () => string;`
      ).join('\n')
      mappedDemo.result = `interface Base {\n${interfaceProps}\n}\n\ntype GettersBase = {\n${getters}\n};`
      break
    case 'pickByType':
      mappedDemo.result = `interface Base {\n${interfaceProps}\n}\n\ntype StringProps = {\n  [P in keyof Base as Base[P] extends string ? P : never]: Base[P];\n};`
      break
  }
}

// 类型推导演示
const inferenceDemo = reactive({
  return: 'ReturnType<typeof fn>',
  parameter: 'Parameters<typeof fn>',
  type: 'return',
  input: '',
  result: ''
})

const processInference = () => {
  if (!inferenceDemo.input) {
    inferenceDemo.result = '请输入示例代码'
    return
  }

  switch (inferenceDemo.type) {
    case 'return':
      inferenceDemo.result = `function ${inferenceDemo.input}() {\n  return { id: 1, name: 'test' };\n}\n\ntype Result = ReturnType<typeof ${inferenceDemo.input}>;`
      break
    case 'parameter':
      inferenceDemo.result = `function ${inferenceDemo.input}<T>(value: T) {\n  return value;\n}\n\ntype Param = Parameters<typeof ${inferenceDemo.input}>[0];`
      break
    case 'context':
      inferenceDemo.result = `const handler = (event: { target: HTMLElement }) => {\n  console.log(event.target.${inferenceDemo.input});\n};`
      break
    case 'guard':
      inferenceDemo.result = `function is${inferenceDemo.input}(value: unknown): value is ${inferenceDemo.input} {\n  return typeof value === '${inferenceDemo.input.toLowerCase()}';\n}`
      break
  }
}
</script>

<style scoped>
.typescript-demo {
  padding: 2rem;
}

.section-title {
  font-size: 2.5rem;
  margin-bottom: 2rem;
  text-align: center;
  background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.demo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.demo-card {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 15px;
  padding: 1.5rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  height: fit-content;
}

.demo-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.demo-header h3 {
  font-size: 1.5rem;
  margin: 0;
  color: var(--primary-color);
}

.code-toggle {
  background: rgba(0, 255, 136, 0.1);
  border: 1px solid rgba(0, 255, 136, 0.3);
  color: #00ff88;
  padding: 0.5rem 1rem;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.code-toggle:hover {
  background: rgba(0, 255, 136, 0.2);
}

.demo-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.code-block {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  overflow: hidden;
  max-height: 300px;
  overflow-y: auto;
}

.code-viewer {
  width: 100%;
  margin: 0;
  padding: 1rem;
  background: transparent;
  color: #b8e0d2;
  font-family: 'Fira Code', monospace;
  font-size: 0.9rem;
  line-height: 1.5;
  white-space: pre-wrap;
  overflow-x: auto;
}

.feature-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.feature-item {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  transition: background-color 0.3s ease;
  overflow: hidden;
}

.feature-item:hover {
  background: rgba(0, 0, 0, 0.3);
}

.feature-label {
  color: var(--primary-color);
  white-space: nowrap;
  margin-right: 1rem;
}

.feature-value {
  font-family: monospace;
  text-align: right;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.interactive-demo {
  margin-top: 1rem;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}

.input-group {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.input-group input {
  flex: 1;
  min-width: 150px;
  padding: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.2);
  color: var(--text-color);
}

.input-group select {
  min-width: 100px;
  padding: 0.5rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  background: rgba(0, 0, 0, 0.2);
  color: var(--text-color);
}

.result-display {
  padding: 1rem;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  white-space: pre-wrap;
  font-family: 'Fira Code', monospace;
  font-size: 0.9rem;
  line-height: 1.5;
  max-height: 200px;
  overflow-y: auto;
}

button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 5px;
  background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 255, 136, 0.2);
}

/* 自定义滚动条样式 */
.code-block::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.code-block::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.code-block::-webkit-scrollbar-thumb {
  background: rgba(0, 255, 136, 0.3);
  border-radius: 4px;
}

.code-block::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 255, 136, 0.4);
}

@media (max-width: 1200px) {
  .demo-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .typescript-demo {
    padding: 1rem;
  }

  .section-title {
    font-size: 2rem;
  }

  .input-group {
    flex-direction: column;
  }

  .input-group input,
  .input-group select,
  .input-group button {
    width: 100%;
    min-width: 0;
  }

  .feature-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }

  .feature-value {
    text-align: left;
  }
}
</style> 